package com.yenroc.ho.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author： heyanpeng
 * @date： 2021/7/27
 */
@Component
public class NettyClient {

    private final Logger log = LoggerFactory.getLogger(NettyClient.class);


    public static Channel channel = null;

    private static ExecutorService executorService = Executors.newCachedThreadPool();

    public void send(TkMessageVo msg) {
        log.info("发送消息=" + msg);
        channel.writeAndFlush(msg);
    }

    public void start(String hostName, Integer port) throws InterruptedException {
        log.info("NettyClient start...");
        NettyClientHandler clientHandler = new NettyClientHandler();
        // 首先，netty通过ServerBootstrap启动服务端
        Bootstrap client = new Bootstrap();

        //第1步 定义线程组，处理读写和链接事件，没有了accept事件
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        client.group(eventLoopGroup);
        //第2步 绑定客户端通道
        client.channel(NioSocketChannel.class);

        //第3步 给NIoSocketChannel初始化handler， 处理读写事件
        client.handler(new NettyClientInitializer());

        ChannelFuture future = client.connect(hostName, port).sync();
        channel = future.channel();
//        future.channel().closeFuture().sync();
    }


}
